﻿using System;
using System.Windows;
using System.Windows.Interactivity;
using GameLogic.Controls;

namespace GameLogic.Logic
{
    // Template for Triggers depending on the GameLoop behavior
    public abstract class GameLoopTrigger<T> : EventTriggerBase<T> where T : FrameworkElement
    {
        private GameLoopFinder gameLoopFinder;

        protected GameLoop GameLoop
        {
            get { return this.gameLoopFinder.GameLoop; }
        }

        protected override void OnSourceChanged(T oldSource, T newSource)
        {
            base.OnSourceChanged(oldSource, newSource);
            this.gameLoopFinder = new GameLoopFinder(this.Source);

            if (this.gameLoopFinder.GameLoop != null)
            {
                this.OnGameLoopInitialized();
            }
            else
            {
                this.gameLoopFinder.OnGameLoopLoaded += this.OnGameGameLoopLoaded;
            }
        }

        private void OnGameGameLoopLoaded(object sender, EventArgs e)
        {
            this.OnGameLoopInitialized();
        }

        protected virtual void OnGameLoopInitialized()
        {

        }

        protected override string GetEventName()
        {
            return string.Empty;
        }

        protected override void OnDetaching()
        {
            base.OnDetaching();
            this.gameLoopFinder.OnGameLoopLoaded -= this.OnGameGameLoopLoaded;
            this.gameLoopFinder = null;
        }
    }
}
